import requests
import json
import urllib3
from config import API_CONFIG, SYSTEM_PROMPT

# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class SimpleChatAssistant:
    def __init__(self):
        self.api_key = API_CONFIG["api_key"]
        self.url = API_CONFIG["base_url"]
        self.model = API_CONFIG["model"]
    
    def chat(self, message, history):
        """与AI助手对话"""
        # 构建消息历史
        messages = [{"role": "system", "content": SYSTEM_PROMPT}]
        
        # 添加对话历史
        for user_msg, bot_msg in history:
            messages.append({"role": "user", "content": user_msg})
            messages.append({"role": "assistant", "content": bot_msg})
        
        # 添加当前消息
        messages.append({"role": "user", "content": message})
        
        # 准备请求
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {self.api_key}'
        }
        data = {
            "model": self.model,
            "messages": messages
        }
        
        # 发送请求
        try:
            response = requests.post(self.url, headers=headers, data=json.dumps(data), verify=False)
            
            if response.status_code == 200:
                result = response.json()
                return result["choices"][0]["message"]["content"]
            else:
                return f"请求失败: {response.status_code}"
        except Exception as e:
            return f"网络错误: {str(e)}"